package com.weme.common.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.weme.common.R

class SmoothImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatImageView(context!!, attrs, defStyleAttr) {

    private var path: Path = Path()
    private var rectF: RectF = RectF()
    private var leftRadius = 0F
    private var rightRadius = 0F
    private var topRadius = 0F
    private var bottomRadius = 0F
    var rectColor = Color.WHITE

    var roundPath: SmootRoundedPath = SmootRoundedPath()

    init {
        setLayerType(LAYER_TYPE_SOFTWARE, null)
        val a = context.obtainStyledAttributes(attrs, R.styleable.SmoothRoundedRectView, defStyleAttr, 0)
        val cornerRadius = a.getDimensionPixelSize(R.styleable.SmoothRoundedRectView_radius, -1)
        leftRadius = a.getDimensionPixelSize(R.styleable.SmoothRoundedRectView_rightTopRadius, cornerRadius).toFloat()
        rightRadius = a.getDimensionPixelSize(R.styleable.SmoothRoundedRectView_leftBottomRadius, cornerRadius).toFloat()
        topRadius = a.getDimensionPixelSize(R.styleable.SmoothRoundedRectView_rightBottomRadius, cornerRadius).toFloat()
        bottomRadius = a.getDimensionPixelSize(R.styleable.SmoothRoundedRectView_leftTopRadius, cornerRadius).toFloat()
        rectColor = a.getColor(R.styleable.SmoothRoundedRectView_rectColor, Color.WHITE)
       // scaleType = ScaleType.CENTER_CROP
        a.recycle() // 释放 TypedArray 资源
        init()
    }

    private fun init() {


    }
    fun setRadius(radius: Float) {
        leftRadius = radius
        rightRadius = radius
        topRadius = radius
        bottomRadius = radius
        invalidate()
    }
    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        val w = width
        val h = height
        roundRectSet(w, h)
    }


    private fun roundRectSet(width: Int, height: Int) {
        rectF[0f, 0f, width.toFloat()] = height.toFloat()
    }

    override fun draw(canvas: Canvas) {
        canvas.save() // 绘制圆角矩形路径
        path = roundPath.getSmoothRoundPath(rectF, Math.max(leftRadius, 0f), Math.max(topRadius, 0f), Math.max(rightRadius, 0f), Math.max(bottomRadius, 0f))

        canvas.clipPath(path)
        super.draw(canvas)
    }


}